﻿using System;
using System.IO;
using System.Text.RegularExpressions;

namespace ZhhbSoft.Data
{
    /// <summary>
    ///用于连接MsAccess 的 DbProvider
    /// </summary>
    public class MsAccessDbProvider : OleDbDbProvider
    {
        private string _filePath = "";
        public MsAccessDbProvider()
            : this("")
        {
        }

        public MsAccessDbProvider(string strConnectionString)
        {
            if (strConnectionString == null)
            {
                OnError(new ArgumentNullException("strConnectionString"));
                return;
            }
            _strRawConnectionString = strConnectionString;
        }

        public override string CreateConnectionString(params string[] strItems)
        {
            if (strItems == null || strItems.Length <= 0 || string.IsNullOrEmpty(strItems[0]))
            {
                _filePath = "";
                return _filePath;
            }
            if (File.Exists(strItems[0]))
            {
                _filePath = new FileInfo(strItems[0]).FullName;
                return string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", _filePath);
            }
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + strItems[0]))
            {
                _filePath = AppDomain.CurrentDomain.BaseDirectory + strItems[0];
                return string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", _filePath);
            }
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "App_Data/" + strItems[0]))
            {
                _filePath = AppDomain.CurrentDomain.BaseDirectory + "App_Data/" + strItems[0];
                return string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", _filePath);
            }
            Regex regex = new Regex(@"[A-Z]:(\\[\w\.]+)*", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            Match match = regex.Match(strItems[0]);
            if (match != null)
            {
                _filePath = match.Value;
            }
            return strItems[0];
        }
        public override long DataFileSize
        {
            get
            {
                if (string.IsNullOrEmpty(_strConnectionString) && !string.IsNullOrEmpty(_strRawConnectionString))
                {
                    _strConnectionString = CreateConnectionString(_strRawConnectionString);
                }
                if (File.Exists(_filePath))
                {
                    return new FileInfo(_filePath).Length;
                }
                return 0;
            }
        }
    }
}